#include <myhead.h>
#include "service.h"
#include "dao.h"
#include "mypkg.h"

int group_service_mygrp(char* username, char* sendbuf, int* bufLen){
	//查询我所在的组
	char result[500]={0};
	int ret=tbl_group_mygroup(username, result);
	printf("username=[%s], ret=[%d], result=[%s]\n", username, ret, result);
	if(ret < 0){
		*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 2, "ERROR", "查询我所在的群发生异常");
		return -1;
	}
	//
	char buf2[20];
	sprintf(buf2,"%d",ret);
	*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 3, "OK", buf2, result);
	return 0;
}

int group_service_mem(char* groupname, char* sendbuf, int* bufLen){
	//查询组员
	char result[500]={0};
	int ret=tbl_group_groupmembers(groupname, result);
	if(ret < 0){
		*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 2, "ERROR", "查询我所在的群成员异常");
		return -1;
	}
	//
	char buf2[20];
	sprintf(buf2,"%d",ret);
	*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 3, "OK", buf2, result);
	return 0;
}

int group_service_add(char* username, char* groupname, char* sendbuf, int* bufLen){
	char errmsg[100]={0};
	int ret=tbl_group_insert(groupname,username, errmsg);
	if(ret == 19){
		*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 2, "ERROR", "该组已存在，该用户已经在该组中");
		return -1;
	}
	if(ret < 0){
		*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 2, "ERROR", errmsg);
		return -1;
	}
	//
	*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 2, "OK", "成功");
	return 0;
}

int group_service_chat(char* username,char* groupname, char* msg,int msglen, char* sendbuf, int* bufLen){
	//查询群成员
	char result[500]={0};
	int cnt=tbl_group_groupmembers(groupname, result);
	if(cnt < 0){
		*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 2, "ERROR", "查询我所在的群成员异常");
		return -1;
	}
	if(cnt == 0){
		*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 2, "ERROR", "该群不存在");
		return -1;
	}
	//查询并统计在线情况
	int online=0;
	char onlineName[1000]={0};
	int offline=0;
	char offlineName[1000]={0};
	for(int i=0;i<cnt;i++){
		char* touser=NULL;
		if(i == 0)
			touser=strtok(result, "\n");
		else
			touser=strtok(NULL, "\n");
		//判断是否在线，并获取ip地址
		ol_data_t* data=ol_link_findByName(touser);
		if(data == NULL|| (time(NULL)-data->hearttime)>ONLINE_SECOND){
			offline++;
			strcat(offlineName, touser);
			strcat(offlineName, ",");
			continue;
		}
		//在线
		service_sendMsg(touser, msg, msglen);
		online++;
		strcat(onlineName, touser);
		strcat(onlineName, ",");
	}
	//回复报文
	if(onlineName[strlen(onlineName)-1] == ',')
		onlineName[strlen(onlineName)-1]=0;
	if(offlineName[strlen(offlineName)-1] == ',')
		offlineName[strlen(offlineName)-1]=0;

	char buf2[50]={0};
	sprintf(buf2, "%d", online);
	char buf3[50]={0};
	sprintf(buf3, "%d", offline);
	*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 5, "OK", buf2, onlineName, 
			buf3, offlineName);
	return 0;
}

